<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
  <view class="bargain-list" :class="'bg-'+theme.backgroundColor">
    <cu-custom :isBack="true" :bgColor="showBg?'bg-'+theme.backgroundColor:''">
      <block slot="backText">返回</block>
      <block slot="content">限时秒杀</block>
      <block slot="right"><text @click="shareShowFun" class=" text-sm text-white align-center margin-right-xs"><text class="cuIcon-forward"></text></text></block>
    </cu-custom>
    <view class="seckill">
      <image class="seckill-image" src="https://joolun-plus-1313274050.cos.ap-nanjing.myqcloud.com/joolun-plus-uniapp/seckill-bg.png"></image>
      <scroll-view scroll-x class="nav text-center padding-left padding-right seckill-time" scroll-with-animation :scroll-left="scrollLeft">
        <view class="navItem flex-sub" :class="index==TabCur?'text-white ':''" v-for="(item,index) in seckillList" :key="index"
              @tap="tabSelect($event,item)" :data-id="index">
          <view class="text-sm">{{item.hallTime+':00'}}</view>
          <view v-if="index==TabCur" class="cu-tag bg-white sm round text-red text-sm">
            {{curHour==item.hallTime?'正在疯抢':curHour>item.hallTime?'已结束':'即将开始'}}
          </view>
          <view v-else class="text-white text-xs">{{curHour==item.hallTime?'正在疯抢':curHour>item.hallTime?'已结束':'即将开始'}}</view>
        </view>
      </scroll-view>
      <view class="cu-bar justify-center ">
        <view class="text-sm">
          <text class="line margin-right-xs"></text>
          <text v-if="outTime>0">本场还剩:</text><count-down  v-if="outTime>0" :outTime="outTime" :textColor="'white'" @countDownDone="countDownDone"></count-down><text v-show="outTime>0">结束</text>
          <text v-show="outTime==0">本场已结束</text>
          <text v-show="outTime<0">本场暂未开始</text>

          <text class="line margin-left-xs"></text>
        </view>
      </view>
      <view class="article no-card">
        <view class="goods-item margin-top padding-bottom padding-top" v-for="(item, index) in listSeckillGoodsInfo" :key="index">
          <navigator v-if="theme.showType!='2'" class="padding-lr " hover-class="none" :url="'/pages/shop/shop-detail/index?id=' + item.shopInfo.id">
            <view class="cu-avatar sm radius" :style="'background-image:url(' + item.shopInfo.imgUrl + ')'"></view>
            <text class="text-black margin-left-sm">{{item.shopInfo.name}}</text>
            <text class="cuIcon-right text-sm"></text>
          </navigator>
          <view class="flex padding-xs padding-bottom align-center padding-top">
            <image :src="item.picUrl" mode="aspectFill" class="row-img margin-left-sm"></image>
            <view class="margin-left-sm seckill-information">
              <view class="text-black text-df overflow-2 padding-right-sm">{{item.name}}</view>
              <view class="flex justify-start margin-top-sm align-center">
                <view class="cu-capsule round">
                  <view class='cu-tag bg-red text-sm' :class="'bg-'+theme.backgroundColor">秒杀价</view>
                  <view class="cu-tag line-red text-price text-bold text-df text-red padding-left-xs">{{item.seckillPrice}}</view>
                </view>
                <view class="text-price text-decorat text-gray margin-left-sm">{{item.goodsSku.salesPrice}}</view>
              </view>
              <view class="regmen margin-top-sm padding-right">
                <view class="text-sm text-gray">限量{{item.limitNum}}件，已售{{item.seckillNum}}件</view>
                <view class="cu-progress round margin-top-sm progress-bar">
                  <view class="bg-red" :style="'width:'+item.progress+'%'">
                    <text class="margin-left percentage">{{item.progress}}%</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="flex justify-center margin-top-sm">
            <navigator class="cu-btn round shadow-blur btn-enter" :class="'bg-'+theme.backgroundColor" hover-class="none"
                       :url="'/pages/seckill/seckill-detail/index?seckillHallInfoId=' + item.seckillHallInfo.id">
              {{curHour==curSeckillHall.hallTime?'马上去抢':'查看详情'}}
            </navigator>
          </view>
        </view>
      </view>
      <view :class="'cu-load ' + (loadmore?'loading':'over') + ' bg-'+theme.backgroundColor"></view>
    </view>
    <!-- 分享组件 -->
    <share-component v-model="showShare" :shareParams="shareParams"></share-component>
  </view>
</template>

<script>
/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
const util = require("utils/util.js");
const app = getApp();
import api from '@/utils/api';
import countDown from "@/components/count-down/index";
import shareComponent from "@/components/share-component/index"

export default {
  components:{
    shareComponent,
    countDown
  },
  watch:{
    curHour(){}
  },
  data() {
    return {
      showBg: false, //是否显示背景色
      CustomBar: this.CustomBar,
      theme: app.globalData.theme, //全局颜色变量
      page: {
        searchCount: false,
        current: 1,
        size: 10,
        ascs: 'sort',
        //升序字段
        descs: ''
      },
      parameter: {},
      loadmore: true,
      listSeckillGoodsInfo: [],//当前时间场次的秒杀商品集合
      seckillList: [],
      curSeckillHall: {//当前会场

      },
      outTime: -1,
      TabCur: 0,
      scrollLeft: 0,
      color: 'red',
      loading: false,
      modalName: '',
      active: false,
      curHour: 0, //当前小时
      curLocalUrl: '',
      showShare: false,
      shareParams: {}
    };
  },

  props: {},

  //页面滑动 监听事件
  onPageScroll(e){
    if (e.scrollTop > 20) {
      this.showBg = true;
    } else {
      this.showBg = false;
    }
  },
  onShow() {},

  onLoad: function(options) {
    if(options.shopId){
      this.parameter.shopId = options.shopId
    }
    this.curHour = this.$moment().format("H");
    app.initPage().then(res => {
      this.seckillhallList();
    });
    let that = this;
    setTimeout(function() {
      that.loading = true
    }, 500)
  },

  onReachBottom() {
    if (this.loadmore) {
      this.page.current = this.page.current + 1;
      this.seckillhallList();
    }
  },

  onPullDownRefresh() {
    // 显示顶部刷新图标
    uni.showNavigationBarLoading();
    this.refresh(); // 隐藏导航栏加载框

    uni.hideNavigationBarLoading(); // 停止下拉动作

    uni.stopPullDownRefresh();
  },

  onShareAppMessage: function() {
    let title = '限时秒杀，抢到就是赚到！';
    let imageUrl = 'https://joolun-mall.oss-cn-hangzhou.aliyuncs.com/1588172823711715328/material/902203a6-2158-49e8-980e-ee592d180676.png';
    if(this.listSeckillGoodsInfo.length>0){//使用第一个商品的秒杀名字和图片作为分享内容
      let item = this.listSeckillGoodsInfo[0]
      title = item.name
      imageUrl = item.picUrl
    }
    let path = 'pages/seckill/seckill-list/index?'
    const userInfo = uni.getStorageSync('user_info')
    const userCode = userInfo ? 'sharer_user_code=' + userInfo.userCode : ''
    path = path + userCode;
    return {
      title: title,
      path: path,
      imageUrl: imageUrl,
      success: function(res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res.errMsg);
        }
      },
      fail: function(res) { // 转发失败
      }
    };
  },
  methods: {
    shareShowFun() {
      // #ifdef H5
      this.curLocalUrl = util.setH5ShareUrl();
      // #endif
      // #ifdef APP-PLUS
      this.curLocalUrl = util.setAppPlusShareUrl();
      // #endif
      let desc = '长按识别小程序码';

      let shareTitle = '限时秒杀，抢到就是赚到！';
      let shareImg = 'https://joolun-mall.oss-cn-hangzhou.aliyuncs.com/1588172823711715328/material/902203a6-2158-49e8-980e-ee592d180676.png';

      if(this.listSeckillGoodsInfo.length>0){//使用第一个商品的秒杀名字和图片作为分享内容
        let item = this.listSeckillGoodsInfo[0]
        shareTitle = item.name
        shareImg = item.picUrl
      }
      // #ifdef H5 || APP-PLUS
      desc = '长按识别二维码';
      // h5的海报分享的图片有的有跨域问题，所以统一转成base64的
      // 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
      shareImg = util.imgUrlToBase64(shareImg);
      // #endif
      //海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
      let posterConfig = {
        width: 750,
        height: 1280,
        backgroundColor: '#fff',
        debug: false,
        blocks: [{
          width: 690,
          height: 808,
          x: 30,
          y: 183,
          borderWidth: 2,
          borderColor: '#ff1c11',
          borderRadius: 20
        }],
        texts: [{
          x: 30,
          y: 113,
          baseLine: 'top',
          text: '限时秒杀，抢到就是赚到！',
          fontSize: 38,
          color: '#080808'
        }, {
          x: 360,
          y: 1123,
          baseLine: 'top',
          text: shareTitle,
          fontSize: 28,
          color: '#929292'
        }],
        images: [{
          width: 634,
          height: 755,
          x: 59,
          y: 210,
          url: shareImg
        }, {
          width: 230,
          height: 230,
          x: 92,
          y: 1020,
          url: null,
          qrCodeName: 'qrCodeName', // 二维码唯一区分标识
        }]
      };
      let userInfo = uni.getStorageSync('user_info');

      if (userInfo && userInfo.headimgUrl) {
        //如果有头像则显示
        posterConfig.images.push({
          width: 62,
          height: 62,
          x: 30,
          y: 30,
          borderRadius: 62,
          url: userInfo.headimgUrl
        });
        posterConfig.texts.push({
          x: 113,
          y: 61,
          baseLine: 'middle',
          text: userInfo.nickName,
          fontSize: 32,
          color: '#8d8d8d'
        });
      }


      // let path = 'pages/seckill/seckill-detail/index?seckillHallInfoId=' + this.seckillHallInfoId;
      // this.curLocalUrl = '&seckillHallInfoId=' + this.seckillHallInfoId;
      this.shareParams = {
        title: '限时秒杀',
        desc: shareTitle,
        imgUrl: shareImg,
        url: this.curLocalUrl,
        scene: '',
        page: 'pages/seckill/seckill-list/index',
        posterConfig: posterConfig
      }
      this.showShare = true;
    },
    countDownDone() {
      this.seckillhallList();
    },
    seckillhallList() {
      let curDate = this.$moment().format("YYYY-MM-DD");
      // let curDate = '2020-09-11';
      let that = this;
      api.seckillhallList(curDate).then(res => {
        let seckillList = res.data;
        this.loadmore = false;
        if(seckillList&&seckillList.length>0){
          let hasSeckill = false;
          this.seckillList = seckillList;
          seckillList.forEach((item,index)=>{
            if(item.hallTime==that.curHour){//默认设置当前小时的秒杀时间，如果没有就设置最近时间的秒杀时间
              this.curSeckillHall = item;
              this.TabCur = index;
              this.scrollLeft = index * 60;
              hasSeckill = true;
              this.getSeckillGoodsData(item.id);
              return;
            }else if(!hasSeckill&&item.hallTime>that.curHour){//秒杀时间必须大于当前时间
              this.curSeckillHall = item;
              this.TabCur = index;
              this.scrollLeft = index * 60;
              hasSeckill = true;
              this.getSeckillGoodsData(item.id);
              return;
            }
          })
          if(!hasSeckill){
            this.curSeckillHall = seckillList[0];
            this.getSeckillGoodsData(this.curSeckillHall.id);
          }
          this.setCountDown();
        }else{
          this.seckillList = [];
        }
      });
    },
    setCountDown(){
      // 设置倒计时时间，
      // 如果当前时间大于会场时间，结束
      // 如果当前时间等于，正在进行中
      // 如果小于暂未开始
      if(this.curSeckillHall.hallTime<this.curHour){
        this.outTime = 0;
      }else if(this.curSeckillHall.hallTime==this.curHour){//计算倒计时多少秒
        let curDateTime = new Date().getTime();//当前时间
        let nextHour = Number(this.curHour) + 1;
        let nextDateTime = this.curSeckillHall.hallDate + ' ' + nextHour + ':00:00';
        let timeTemp = this.$moment(nextDateTime).toDate();
        this.outTime = new Date(timeTemp).getTime() - curDateTime;//下一个整点时间
      }else{
        this.outTime=-1;
      }
    },
    tabSelect(e,item) {
      this.curHour = this.$moment().format("H");
      this.TabCur = e.currentTarget.dataset.id;
      this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
      this.listSeckillGoodsInfo = [];
      if(item){
        item.listSeckillInfo = item.listSeckillInfo? item.listSeckillInfo:[];
        this.curSeckillHall = item;
        this.getSeckillGoodsData(item.id);
      }else{
        this.curSeckillHall = {
          listSeckillInfo: [],
          outTime:0
        };
      }
      this.setCountDown();
    },
    getSeckillGoodsData(id){
      api.seckillinfoPage(Object.assign({seckillHallId:id}, this.page, util.filterForm(this.parameter))).then(res => {
        let listSeckillGoodsInfo = res.data.records;
        listSeckillGoodsInfo.forEach((item,index)=>{
          item.progress = (item.seckillNum/item.limitNum).toFixed(2)*100
        })
        this.listSeckillGoodsInfo = [...this.listSeckillGoodsInfo, ...listSeckillGoodsInfo];
        if (listSeckillGoodsInfo.length < this.page.size) {
          this.loadmore = false;
        }
      });
    },
    refresh() {
      this.loadmore = true;
      this.seckillList = [];
      this.listSeckillGoodsInfo = [];
      this.page.current = 1;
      this.seckillhallList();
    }

  }
};
</script>
<style>
.navItem{
  display: inline-block;
  line-height: 30rpx;
  margin: 0 10rpx;
  padding: 0 20rpx;
}

.seckill-time{
  min-height: 50px;
}

.row-img {
  width: 200rpx !important;
  height: 200rpx !important;
  border-radius: 10rpx;
}

.seckill{
  min-height: 1450rpx;
}

.line{
  display:inline-block;
  width:120rpx;
  border-top:0.5rpx solid #cccccc;
  vertical-align:5px;
  opacity: 0.5;
}

.goods-item{
  background-color: #FFFFFF;
  width: 94%;
  margin: auto;
  border-radius: 10rpx;
  margin-bottom: 40rpx;
}

.seckill-information{
  width: 460rpx;
}

.seckill-image{
  width: 100%;
  height: 420rpx;
  margin-top: -120rpx;
}

.progress-bar{
  height: 16rpx;
}

.percentage{
  color: #ffb04a!important;
}

.btn-enter{
  width: 580rpx;
  height: 76rpx;
}
</style>
